//
//  BaseViewController.swift
//  SwiftScienceChina
//
//  Created by 贾培军 on 2019/12/9.
//  Copyright © 2019 贾培军. All rights reserved.
//

import UIKit

open class SWBaseViewController: UIViewController {
    public var errorView = SWErrorView()
    public var emptyView = SWEmptyView()
    public var dataErrorView = SWDataErrorView()
    public var cutBackItem :Bool = false
    
    @objc var needHideNavigationBar = false
    
    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        debugPrint("%@", #function)
        self.hidesBottomBarWhenPushed = true;
    }
    public convenience init(cutBackItem:Bool) {
        self.init()
        self.cutBackItem = cutBackItem
    }
    required public init?(coder aCoder: NSCoder) {
        super.init(coder: aCoder)
        debugPrint("%@", #function)
    }
    
    deinit{
        debugPrint("----释放-\(self.description)")
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        debugPrint(self.description)
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .init(0xF5F5F5)
        self.edgesForExtendedLayout = []
        
        if !cutBackItem {
            setupback()
        }
        
        // Do any additional setup after loading the view.
    }

    open func customNavigationBar(){
        let vcArray = self.navigationController?.viewControllers
        if (vcArray?.count ?? 0) > 0 && vcArray?.first != self{
            NSLog("initNavLeftBtn")
        }
    }
    
    open func showNavigationBarShadow(){
        self.navigationController?.navigationBar.setShadowWithColor(.init(0xf2f6f7));
    }
    
    open func handleRequestData(data: SWUnhandledRequestData) -> Bool {
        return false
    }
    
    open func handleRequestData(data: SWUnhandledRequestData, view: UIView) -> Bool {
        emptyView.removeFromSuperview()
        errorView.removeFromSuperview()
        dataErrorView.removeFromSuperview()
        //        var handled = false
        if data.error == nil && data.requestDataExist{
            return false
        }
        
        if let error = data.error {
            if data.localDataExist {
                view.makeToast(error.localizedDescription)
            }else{
                if error.code == NSURLErrorNetworkConnectionLost || error.code == NSURLErrorTimedOut {
                    view.addSubview(errorView)
                    errorView.snp.makeConstraints { (m) in
                        m.edges.equalTo(0)
                    }
                }else{
                    view.addSubview(dataErrorView)
                    dataErrorView.snp.makeConstraints { (m) in
                        m.edges.equalTo(0)
                    }
                }
            }
        }else{
            view.addSubview(emptyView)
//            emptyView.backgroundColor = .red
            emptyView.snp.makeConstraints { (m) in
                m.edges.equalTo(0)
            }
        }
        return true
    }
    
    open func handleRequestError(retryBlock: @escaping RetryBlock) {
        errorView.bringSubviewToFront(view)
        errorView.retryBlock = retryBlock
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        debugPrint(self.description)
    }
    
    open override var shouldAutorotate: Bool{
        return false
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
}

extension SWBaseViewController{
    private struct AssociatedKey {
        static var rightIdentifier: String = "rightIdentifier"
        static var leftIdentifier: String = "leftIdentifier"
    }
    open var leftAction:(()->Void)?{
        get{
            return objc_getAssociatedObject(self, &AssociatedKey.leftIdentifier) as? () -> Void
        }
        set{
            objc_setAssociatedObject(self, &AssociatedKey.leftIdentifier, newValue, .OBJC_ASSOCIATION_COPY)
        }
    }
    open var rightAction:(()->Void)?{
        get{
            return objc_getAssociatedObject(self, &AssociatedKey.rightIdentifier) as? () -> Void
        }
        set{
            objc_setAssociatedObject(self, &AssociatedKey.rightIdentifier, newValue, .OBJC_ASSOCIATION_COPY)
        }
    }
    open func adjustInset(button:UIButton, isLeft:Bool) {
        if #available(iOS 11.0, *) {
            if isLeft {
//                button.imageEdgeInsets = .init(top: 0, left: -21, bottom: 0, right: 21)
            }else{
                button.imageEdgeInsets = .init(top: 0, left: 6, bottom: 0, right: -6)
            }
        }
    }
    
    @objc open func rightButtonAction() {
        rightAction?()
    }
    
    @objc open func leftButtonAction() {
        leftAction?()
    }
    
    open func setupRight(title:String, action:@escaping ()->Void) {
        self.rightAction = action
        
        let b: UIButton = UIButton()
        b.setTitle(title, for: .normal)
        b.setTitleColor(.init(0x333333), for: .normal)
        b.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        b.titleEdgeInsets = .init(top: 0, left: 0, bottom: 0, right: -10)
        let size: CGSize = title.size(withAttributes: [NSAttributedString.Key.font:b.titleLabel?.font as Any])
        b.frame = .init(x: 0, y: 0, width: size.width, height: size.height)
        b.addTarget(self, action: #selector(rightButtonAction), for: .touchUpInside)
        //[self adjustButtonInsetWith:b isLeft:NO];
        let item: UIBarButtonItem = UIBarButtonItem(customView: b)
        navigationItem.rightBarButtonItems = [item]
        
    }
    
    open func setupRight(imageName:String, action:@escaping ()->Void) {
        self.rightAction = action

        let b: UIButton = UIButton()
        b.frame = .init(x: 0, y: 0, width: 20, height: 20)
        b.setImage(.init(imageLiteralResourceName:imageName), for: .normal)
        b.addTarget(self, action: #selector(rightButtonAction), for: .touchUpInside)
        
        adjustInset(button:b, isLeft: false)
        let item: UIBarButtonItem = UIBarButtonItem(customView: b)
        navigationItem.rightBarButtonItems = [item]
        
    }
    open func setupLeft(imageName:String, action:@escaping ()->Void) {
        self.leftAction = action
        let b: UIButton = UIButton()
        b.frame = .init(x: 0, y: 0, width: 20, height: 20)
        b.setImage(.init(imageLiteralResourceName:imageName), for: .normal)
        b.addTarget(self, action: #selector(leftButtonAction), for: .touchUpInside)
        
        adjustInset(button:b, isLeft: true)
        let item: UIBarButtonItem = UIBarButtonItem(customView: b)
        navigationItem.leftBarButtonItems = [item]
        
    }
    
    open func setupback() {
        self.leftAction = { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        let b: UIButton = UIButton()
        b.frame = .init(x: 0, y: 0, width: 20, height: 20)
        let bundle = Bundle.groupBundle(for: SWBaseViewController.self)
        let image = UIImage.init(named: "back", in: bundle, compatibleWith: nil)
        b.setImage(image, for: .normal)
        b.addTarget(self, action: #selector(leftButtonAction), for: .touchUpInside)

        adjustInset(button:b, isLeft: true)
        let item: UIBarButtonItem = UIBarButtonItem(customView: b)
        navigationItem.leftBarButtonItems = [item]

    }
}
